package com.rjh.concurrent.monitor;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j(topic = "c.WaitNotifyTest")
public class WaitNotifyTest {

    private static final Object OBJECT = new Object();

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            synchronized (OBJECT) {
                log.debug("t1 running");
                try {
                    OBJECT.wait(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("t1 after");
            }
        }, "t1");
        t1.start();

        Thread t2 = new Thread(() -> {
            synchronized (OBJECT) {
                log.debug("t2 running");
                try {
                    OBJECT.wait(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("t2 after");
            }
        }, "t2");
        t2.start();


        TimeUnit.SECONDS.sleep(2);
        synchronized (OBJECT){
            OBJECT.notify();
        }
    }
}


@Slf4j(topic = "c.Food")
class Food{


    public static void main(String[] args) {
        Food food = new Food();

        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                food.create();
            }
        }, "create");


        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                food.toke();
            }
        }, "toke");


        t1.start();
        t2.start();


    }

    int size = 0;

    public void create(){
        synchronized (this){
            if (size>0){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            size += 1;
            log.debug("create food {}",size);
            this.notify();
        }
    }

    public void toke(){
        synchronized (this){
            if (size==0){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            size -= 1;
            log.debug("toke food {}",size);
            this.notify();
        }
    }

}
